using System.Linq;
using SpreadsheetGear;
using WorkbookDesigner.Addons.SpreadsheetEditor.Presenter;

namespace WorkbookDesigner.Addons.SpreadsheetEditor.Model
{
    public sealed class ActionNewPrompt : ActionModel
    {
        public ActionNewPrompt(PromptModel template, PromptModel insertBelow) : base(OpType.New)
        {
            Template = template;
            InsertBelow = insertBelow;
        }
        public PromptModel InsertBelow { get; }
        public override void Execute(IMission m)
        {
            var plist = m.GetPromptList(false);
            bool exist = plist.Count(x => x.Name == Template.Name) > 0;
            if (exist)
                return;
            var p = plist.FirstOrDefault(x => x.Name == InsertBelow.Name);
            if (p == null)
            {
                bool visible = Template.VisiblePrompt;
                IWorksheet sheet = m.Workbook.Worksheets["Prompts"];
                int count = visible ? sheet.Cells.GetMaxRow(0) : sheet.Cells.GetMaxRow(1);
                IRange newP = sheet.Cells[count, 0].EntireRow;
                newP.Insert(InsertShiftDirection.Down);
                Template.AddTo(newP);
            }
            else
            {
                IRange nextRow = p.Row[1, 0].EntireRow;
                nextRow.Insert(InsertShiftDirection.Down);
                Template.AddTo(nextRow);
            }
        }
    }
}